package routers

import (
	"encoding/json"
	"net/http"
	"strconv"

	"shqsoft.cn/pas3ui/base"
	"shqsoft.cn/pas3ui/popedom"

	"strings"

	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
)

// GetMenuTree 获取权限树
func GetMenuTree(c echo.Context) error {
	treeNodes, err := popedom.GetPermissionTree()
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, treeNodes)
}

// GetMenuUserTree 获取用户树
func GetMenuUserTree(c echo.Context) error {
	userIDStr := c.FormValue("UserPerms")
	treeNodes, err := popedom.GetOrganTree()
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	_treeNodes := make([]popedom.TreeNode, 0)
	_children := make([]popedom.TreeNode, 0)
	if userIDStr == "" {
		_treeNodes = treeNodes
	} else {
	OuterLoop:
		for _, v := range treeNodes {
			// 判断当前节点是否包含userIDStr
			if strings.Contains(v.Title, userIDStr) {
				// 将当前节点添加到_treeNodes中
				_treeNodes = append(_treeNodes, v)
				// 结束当前循环
				continue OuterLoop
			}
			// 判断当前节点是否有子节点
			if len(v.Children) > 0 {
				// 遍历当前节点的子节点
				for _, vv := range v.Children {
					// 判断当前子节点是否包含userIDStr
					if strings.Contains(vv.Title, userIDStr) {
						// 将当前子节点添加到_children中
						_children = append(_children, popedom.TreeNode{
							Key:      vv.Key,
							Title:    vv.Title,
							Children: []popedom.TreeNode{},
						})
						// 将当前节点添加到_treeNodes中
						_treeNodes = append(_treeNodes, popedom.TreeNode{
							Key:      v.Key,
							Title:    v.Title,
							Children: _children,
						})
						// 结束当前循环
						continue OuterLoop
					}
					// 判断当前子节点是否有子节点
					if len(vv.Children) > 0 {
						// 遍历当前子节点的子节点
						for _, vvv := range vv.Children {
							// 判断当前子子节点是否包含userIDStr
							if strings.Contains(vvv.Title, userIDStr) {
								// 将当前子子节点添加到_children中
								_children = append(_children, popedom.TreeNode{
									Key:      vvv.Key,
									Title:    vvv.Title,
									Children: []popedom.TreeNode{},
								})
								// 将当前子节点添加到_treeNodes中
								_treeNodes = append(_treeNodes, popedom.TreeNode{
									Key:      vv.Key,
									Title:    vv.Title,
									Children: _children,
								})
								// 结束当前循环
								continue OuterLoop
							}
						}
					}
				}
			}
		}
	}
	return c.JSON(http.StatusOK, _treeNodes)
}

// GetRolePermsKeys 根据角色ID获取选中权限key
func GetRolePermsKeys(c echo.Context) error {
	rID := c.Param("RoleID")
	if rID == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "角色ID不能为空！")
	}
	rIDInt, err := strconv.Atoi(rID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	checkedkeys, err := popedom.GetCheckedRolePerms(rIDInt)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, checkedkeys)
}

// GetRoleUsersKeys 根据角色ID获取用户
func GetRoleUsersKeys(c echo.Context) error {
	rID := c.Param("RoleID")
	if rID == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "角色ID不能为空！")
	}
	rIDInt, err := strconv.Atoi(rID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	checkedkeys, err := popedom.GetCheckedRoleUsers(rIDInt)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, checkedkeys)
}

// SaveRolePerms 保存角色权限
func SaveRolePerms(c echo.Context) error {
	rID := c.Param("RoleID")
	if rID == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "角色ID不能为空！")
	}
	rIDInt, err := strconv.Atoi(rID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	var rolePerms []string
	jsonStr := c.FormValue("RolePerms")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "rolePerms不能为空！")
	}
	err = json.Unmarshal([]byte(jsonStr), &rolePerms)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	// if l := len(rolePerms); l == 0 {
	// 	return echo.NewHTTPError(http.StatusBadRequest, "rolePerms不能为空数组！")
	// }
	var roleUsers []string
	jsonStr = c.FormValue("RoleUsers")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "roleUsers不能为空！")
	}
	err = json.Unmarshal([]byte(jsonStr), &roleUsers)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	// if l := len(roleUsers); l == 0 {
	// 	return echo.NewHTTPError(http.StatusBadRequest, "roleUsers不能为空数组！")
	// }
	premMap := make(map[int]string)
	for _, rp := range rolePerms {
		pType := strings.Split(rp, ":")
		if len(pType) < 2 {
			continue
		}
		pID, err := strconv.Atoi(pType[0])
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
		}
		pts, ok := premMap[pID]
		if !ok {
			pts = ""
		} else {
			pts = pts + ","
		}
		pts = pts + pType[1]
		var qxsl int
		sql := `select COUNT(*) from "t_Permission" tp where  "ParentPermissionId" = 230710 and "ID" = ?`
		err = base.MYDB.Raw(sql, pID).Row().Scan(&qxsl)
		if err != nil {
			return err
		}
		if (qxsl == 1 && strings.Contains(pts, "4")) && (rIDInt != 2 && rIDInt != 15) {
			if len(roleUsers) == 0 {
				return echo.NewHTTPError(http.StatusBadRequest, "考核报表下-绩效发放模块下的所有菜单的查看所有部门权限只能授予角色分行领导和系统管理员；只能授予计划财务部门下面的员工")
			}
			for _, ry := range roleUsers {
				rType := strings.Split(ry, ":")
				if len(rType) < 2 {
					continue
				}
				rhID, err := strconv.Atoi(rType[1])
				if err != nil {
					return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
				}
				var rsl int
				sql := `select COUNT(*) from "T_SysUser" where "ID" = ? and  "OrganID" = 216607`
				base.MYDB.Raw(sql, rhID).Row().Scan(&rsl)
				if rsl == 0 {
					return echo.NewHTTPError(http.StatusBadRequest, "考核报表下-绩效发放模块下的所有菜单的查看所有部门权限只能授予角色分行领导和系统管理员；只能授予计划财务部门下面的员工")
				}
			}
		}
		premMap[pID] = pts
	}
	uIDs := make([]int, 0, len(roleUsers))
	for _, ru := range roleUsers {
		rUIDS := strings.Split(ru, ":")
		if len(rUIDS) < 2 {
			continue
		}
		uID, err := strconv.Atoi(rUIDS[1])
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
		}
		// if rIDInt == 2 {
		// 	var rsl int
		// 	sql := `select COUNT(*) from "T_SysUser" where "ID" = ? and ("OrganID" = 216612 or "OrganID" = 216607)`
		// 	err := base.MYDB.Raw(sql, uID).Row().Scan(&rsl)
		// 	if err != nil {
		// 		return err
		// 	}
		// 	if rsl == 0 {
		// 		return echo.NewHTTPError(http.StatusBadRequest, "分行领导角色只能授予办公室-行长室和计财部下面的员工")
		// 	}
		// } else if rIDInt == 15 {
		// 	if uID != 0 && uID != 79 {
		// 		return echo.NewHTTPError(http.StatusBadRequest, "系统管理员只能授予分行公共及邓文骏")
		// 	}
		// }
		uIDs = append(uIDs, uID)
	}
	err = popedom.GrantPermissionsAndUsersToRole(rIDInt, premMap, uIDs...)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "保存失败")
	}
	return c.JSON(http.StatusOK, "OK")
}

// GetRolePermsKeys 根据用户ID获取选中权限key
func GetUserPermsKeys(c echo.Context) error {
	uID := c.Param("UserID")
	if uID == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "用户ID不能为空！")
	}
	uIDInt, err := strconv.Atoi(uID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	checkedkeys, err := popedom.GetCheckedUserPerms(uIDInt)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, checkedkeys)
}

// GetRoleUsersKeys 根据用户ID获取角色
func GetUserRolesKeys(c echo.Context) error {
	uID := c.Param("UserID")
	if uID == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "用户ID不能为空！")
	}
	uIDInt, err := strconv.Atoi(uID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	checkedkeys, err := popedom.GetCheckedUserRoles(uIDInt)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, checkedkeys)
}

// SaveRolePerms 保存用户权限
func SaveUserPerms(c echo.Context) error {
	uID := c.Param("UserID")
	if uID == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "用户ID不能为空！")
	}
	uIDInt, err := strconv.Atoi(uID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	var userPerms []string
	jsonStr := c.FormValue("UserPerms")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "UserPerms不能为空！")
	}
	err = json.Unmarshal([]byte(jsonStr), &userPerms)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	var userRoles []string
	jsonStr = c.FormValue("UserRoles")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "userRoles不能为空！")
	}
	err = json.Unmarshal([]byte(jsonStr), &userRoles)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	premMap := make(map[int]string)
	for _, up := range userPerms {
		pType := strings.Split(up, ":")
		if len(pType) < 2 {
			continue
		}
		pID, err := strconv.Atoi(pType[0])
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
		}
		pts, ok := premMap[pID]
		if !ok {
			pts = ""
		} else {
			pts = pts + ","
		}
		pts = pts + pType[1]
		var qxsl int
		sql := `select COUNT(*) from "t_Permission" tp where  "ParentPermissionId" = 230710 and "ID" = ?`
		err = base.MYDB.Raw(sql, pID).Row().Scan(&qxsl)
		if err != nil {
			return err
		}
		if strings.Contains(pts, "4") && qxsl != 0 {
			var jhcw, hzs int
			sql := `select COUNT(*) from "T_SysUser" where "ID" = ? and  "OrganID" = 216607`
			err := base.MYDB.Raw(sql, uIDInt).Row().Scan(&jhcw)
			if err != nil {
				return err
			}
			sql = `select COUNT(*) from "T_SysUser" where "ID" = ? and  "OrganID" = 216612`
			err = base.MYDB.Raw(sql, uIDInt).Row().Scan(&hzs)
			if err != nil {
				return err
			}
			if jhcw == 0 && uIDInt != 0 && hzs == 0 {
				return echo.NewHTTPError(http.StatusBadRequest, "考核报表下-绩效发放模块下的所有菜单的查看所有部门权限只能授予角色分行领导和系统管理员；只能授予计划财务部门下面的员工")
			}

		}
		premMap[pID] = pts
	}
	rIDs := make([]int, 0, len(userRoles))
	for _, ur := range userRoles {
		rID, err := strconv.Atoi(ur)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
		}
		// if rID == 2 {
		// 	var rsl int
		// 	sql := `select COUNT(*) from "T_SysUser" where "ID" = ? and ("OrganID" = 216612 or "OrganID" = 216607)`
		// 	err := base.MYDB.Raw(sql, uIDInt).Row().Scan(&rsl)
		// 	if err != nil {
		// 		return err
		// 	}
		// 	if rsl == 0 {
		// 		return echo.NewHTTPError(http.StatusBadRequest, "分行领导角色只能授予办公室-行长室和计财部下面的员工")
		// 	}
		// } else if rID == 15 {
		// 	if uIDInt != 0 && uIDInt != 79 {
		// 		return echo.NewHTTPError(http.StatusBadRequest, "系统管理员只能授予分行公共及邓文骏")
		// 	}
		// }
		rIDs = append(rIDs, rID)
	}

	err = popedom.GrantPermissionsAndRolesToUser(uIDInt, premMap, rIDs...)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "保存失败")
	}
	return c.JSON(http.StatusOK, "OK")
}

// UserPermissionTypesRouter 获取用户指定权限的所有权限ID
func UserPermissionTypesRouter(c echo.Context) error {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	permIDStr := c.Param("PermID")
	if permIDStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "权限ID不能为空！")
	}
	permID, err := strconv.Atoi(permIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "string类型转换int失败")
	}
	pTypes, err := popedom.GetUserPermissionTypes(claims.UserID, permID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err)
	}
	return c.JSON(http.StatusOK, pTypes)
}
